package com.fliad.ai.service;

import com.fliad.ai.entity.AiAgent;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;
import org.noear.wood.DbContext;
import org.noear.wood.annotation.Db;

import java.sql.SQLException;
import java.util.*;
import java.lang.reflect.Field;

/**
 * @author wyl
 * @date 2025年07月10日 21:22
 */
@Component
public class AiAgentService {

    @Db
    DbContext db;

    // 创建
    public Boolean create(AiAgent agent) throws SQLException {
        return insertAgent(agent);
    }

    // 查询单个
    public AiAgent get(Long id) throws SQLException {
        return db.table("ai_agent")
                .whereEq("id", id)
                .selectItem("*", AiAgent.class);
    }

    // 查询列表
    public List<AiAgent> list() throws SQLException {
        return db.table("ai_agent")
                .orderBy("id DESC")
                .selectList("*", AiAgent.class);
    }

    // 更新
    public Boolean update(Long id, AiAgent agent) throws SQLException, IllegalAccessException {
        agent.setId(id);
        Map<String, Object> map = convertToUnderScoreMap(agent);
        return db.table("ai_agent")
                .whereEq("id", id)
                .setMap(map)
                .update() > 0;
    }

    // 删除
    public Boolean delete(Long id) throws SQLException {
        return db.table("ai_agent")
                .whereEq("id", id)
                .delete() > 0;
    }

    // 新增方法：插入代理
    private boolean insertAgent(AiAgent agent) throws SQLException {
        return db.table("ai_agent")
                .setEntity(agent)
                .insert() > 0;
    }

    // 新增方法：保存流程
    public boolean saveFlow(Long id, AiAgent agent) throws SQLException {
        return db.table("ai_agent")
                .whereEq("id", id)
                .setEntity(agent)
                .update() > 0;
    }

    /**
     * 将对象中的字段名从驼峰格式转换为下划线格式，并返回对应的 Map
     */
    private Map<String, Object> convertToUnderScoreMap(Object obj) throws IllegalAccessException {
        Map<String, Object> resultMap = new HashMap<>();
        Class<?> clazz = obj.getClass();

        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);

            // 转换为下划线命名
            String underscoreName = toUnderscore(fieldName);
            // 如果值是ONode类型转化为字符串
            if (value instanceof ONode) {
                value = ((ONode) value).toJson();
            }
            resultMap.put(underscoreName, value);
        }

        return resultMap;
    }

    /**
     * 驼峰命名转下划线命名
     */
    private String toUnderscore(String name) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (Character.isUpperCase(c)) {
                if (i > 0) {
                    result.append("_");
                }
                result.append(Character.toLowerCase(c));
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }
}